package com.azkj.album.view.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.azkj.album.R;
import com.azkj.album.dto.LoginBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.RegisterBean;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.Constants;
import com.azkj.album.network.networkframe.net.HttpsUtil;
import com.azkj.album.network.utils.StoreUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.RegisterPresenter;
import com.azkj.album.presenter.UserPresenter;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.iview.IRegisterView;
import com.azkj.album.view.iview.IUserView;
import com.azkj.album.view.widgets.TitleNavBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity implements IRegisterView, IUserView {

    @BindView(R.id.titleBar)
    TitleNavBar mTitleBar;

    @BindView(R.id.login_nickname)
    EditText mEtName;

    @BindView(R.id.login_phone)
    EditText mEtPhone;

    @BindView(R.id.ll_login_sms)
    LinearLayout mLlSMS;
    @BindView(R.id.login_phone_2)
    EditText mEtPhone2;

    @BindView(R.id.ll_login_sms_2)
    LinearLayout mLlSMS2;

    @BindView(R.id.et_login_code)
    EditText mEtCode;
    @BindView(R.id.tv_send_code)
    TextView mTvSend;

    @BindView(R.id.et_login_code_2)
    EditText mEtCode2;
    @BindView(R.id.tv_send_code_2)
    TextView mTvSend2;


    @BindView(R.id.ll_login_psd)
    LinearLayout mLlPsd;
    @BindView(R.id.ll_login_psd_2)
    LinearLayout mLlPsd2;


    @BindView(R.id.et_login_psd)
    EditText mEtPsd;
    @BindView(R.id.et_login_psd_2)
    EditText mEtPsd2;

    @BindView(R.id.tv_login_psd_visibility)
    ImageView mIvSee;
    @BindView(R.id.tv_login_psd_visibility_2)
    ImageView mIvSee2;

    @BindView(R.id.iv_check)
    ImageView mIvCheck;

    @BindView(R.id.tv_next)
    TextView mTvNext;
    @BindView(R.id.rl_check)
    RelativeLayout mRlCheck;

    boolean isChecked = false;
    private RegisterPresenter mPresenter;
    private UserPresenter mUserPresenter;
    private RegisterBean mRegisterBean;


    // 0注册，1注册设置密码，2忘记密码，3忘记密码设置密码，4修改密码，5修改密码设置密码，6 修改手机号旧号码修改手机号新手机
    private int mType = 0;

    public static void startActivity(Context context, int type, RegisterBean bean) {
        Intent intent = new Intent(context, RegisterActivity.class);
        intent.putExtra("type", type);
        if (bean == null) bean = new RegisterBean();
        intent.putExtra("bean", bean);
        context.startActivity(intent);

    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        mTitleBar.setLeftListener(v -> finish());
        mType = getIntent().getIntExtra("type", 0);
        mRegisterBean = (RegisterBean) getIntent().getSerializableExtra("bean");
        switch (mType) {
            case 0:
                mTitleBar.setTitle("注册");
                mRlCheck.setVisibility(View.VISIBLE);
                mEtName.setVisibility(View.VISIBLE);
                mEtPhone.setVisibility(View.VISIBLE);
                mLlSMS.setVisibility(View.VISIBLE);
                mLlPsd.setVisibility(View.GONE);
                mLlPsd2.setVisibility(View.GONE);
                mTvNext.setText("下一步");
                break;
            case 1:
                mTitleBar.setTitle("注册");
                mRlCheck.setVisibility(View.VISIBLE);
                mEtName.setVisibility(View.GONE);
                mEtPhone.setVisibility(View.GONE);
                mLlSMS.setVisibility(View.GONE);
                mLlPsd.setVisibility(View.VISIBLE);
                mLlPsd2.setVisibility(View.VISIBLE);
                mTvNext.setText("注册，并前往登录");
                isChecked = true;
                mIvCheck.setImageResource(R.mipmap.ic_checked);

                break;
            case 2:
                mTitleBar.setTitle("忘记密码");
                mEtName.setVisibility(View.GONE);
                mEtPhone.setVisibility(View.VISIBLE);
                mLlSMS.setVisibility(View.VISIBLE);
                mLlPsd.setVisibility(View.GONE);
                mLlPsd2.setVisibility(View.GONE);
                mTvNext.setText("下一步");
                break;
            case 3:
                mTitleBar.setTitle("忘记密码");
                mEtName.setVisibility(View.GONE);
                mEtPhone.setVisibility(View.GONE);
                mLlSMS.setVisibility(View.GONE);
                mLlPsd.setVisibility(View.VISIBLE);
                mLlPsd2.setVisibility(View.VISIBLE);
                mTvNext.setText("提交");
                break;
            case 4:
                mTitleBar.setTitle("修改密码");
                mEtName.setVisibility(View.GONE);
                mEtPhone.setVisibility(View.VISIBLE);
                mLlSMS.setVisibility(View.VISIBLE);
                mLlPsd.setVisibility(View.GONE);
                mLlPsd2.setVisibility(View.GONE);
                mTvNext.setText("下一步");
                mEtPhone.setText(ConfigStorage.getInstance().getUserBean().getUserinfo().getMobile());
                mEtPhone.setEnabled(false);
                break;
            case 5:
                mTitleBar.setTitle("修改密码");
                mEtName.setVisibility(View.GONE);
                mEtPhone.setVisibility(View.GONE);
                mLlSMS.setVisibility(View.GONE);
                mLlPsd.setVisibility(View.VISIBLE);
                mLlPsd2.setVisibility(View.VISIBLE);
                mTvNext.setText("提交");
                break;
            case 6:
                mTitleBar.setTitle("修改手机号");
                mEtName.setVisibility(View.GONE);
                mEtPhone.setVisibility(View.VISIBLE);
                mLlSMS.setVisibility(View.VISIBLE);
                mEtPhone2.setVisibility(View.VISIBLE);
                mLlSMS2.setVisibility(View.VISIBLE);

                mLlPsd.setVisibility(View.GONE);
                mLlPsd2.setVisibility(View.GONE);
                mTvNext.setText("提交");
                mEtPhone.setText(ConfigStorage.getInstance().getUserBean().getUserinfo().getMobile());
                mEtPhone.setEnabled(false);
                break;

        }


    }

    @Override
    public void initData() {


    }

    @OnClick({R.id.tv_login_psd_visibility, R.id.tv_login_psd_visibility_2, R.id.tv_send_code, R.id.tv_send_code_2,
            R.id.iv_check, R.id.tv_xieyi1, R.id.tv_xieyi2, R.id.tv_next})
    public void onClick(View v) {
//        if (Utils.isFastClick()) return;
        switch (v.getId()) {
            case R.id.tv_login_psd_visibility:
                if (mEtPsd.getTransformationMethod() == HideReturnsTransformationMethod
                        .getInstance()) {
                    mEtPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mIvSee.setImageResource(R.mipmap.icon_login_eye);
                } else {
                    mEtPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示}
                    mIvSee.setImageResource(R.mipmap.icon_login_eye_open);
                }
                if (!TextUtils.isEmpty(mEtPsd.getText()))
                    mEtPsd.setSelection(mEtPsd.getText().length());
                break;
            case R.id.tv_login_psd_visibility_2:
                if (mEtPsd2.getTransformationMethod() == HideReturnsTransformationMethod
                        .getInstance()) {
                    mEtPsd2.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mIvSee2.setImageResource(R.mipmap.icon_login_eye);
                } else {
                    mEtPsd2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示}
                    mIvSee2.setImageResource(R.mipmap.icon_login_eye_open);
                }
                if (!TextUtils.isEmpty(mEtPsd2.getText()))
                    mEtPsd2.setSelection(mEtPsd2.getText().length());
                break;

            case R.id.tv_send_code:
                sendSMS();
                break;
            case R.id.tv_send_code_2:
                sendSMS2();
                break;

            case R.id.iv_check:
                isChecked = !isChecked;
                mIvCheck.setImageResource(isChecked ? R.mipmap.ic_checked : R.mipmap.ic_uncheck);
                break;
            case R.id.tv_xieyi1:
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "隐私政策");
                intent.putExtra("url", Constants.WEB_PAGE_PROTOCOL_1);
                startActivity(intent);

                break;
            case R.id.tv_xieyi2:
                Intent intent2 = new Intent(this, WebViewActivity.class);
                intent2.putExtra("title", "用户协议");
                intent2.putExtra("url", Constants.WEB_PAGE_PROTOCOL_2);
                startActivity(intent2);
                break;

            case R.id.tv_next:
                next();
                break;
        }
    }

    private void next() {
        if (mType == 0 && !isChecked) {
            ToastUtils.showCenterToast("请阅读并同意《隐私政策》及《用户协议》");
            return;
        }


        if (mType == 0 || mType == 2 || mType == 4 || mType == 6) {

            if (mType == 0 && TextUtils.isEmpty(mEtName.getText().toString().trim())) {
                ToastUtils.showCenterToast("请输入用户名");
                return;
            }
            if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
                ToastUtils.showCenterToast("请输入手机号");
                return;
            }
            if (TextUtils.isEmpty(mEtCode.getText().toString().trim())) {
                ToastUtils.showCenterToast("请输入验证码");
                return;
            }
            mRegisterBean.nickname = mEtName.getText().toString().trim();
            mRegisterBean.phone = mEtPhone.getText().toString().trim();
            mRegisterBean.code = mEtCode.getText().toString().trim();
            if (mType == 6) {
                if (TextUtils.isEmpty(mEtPhone2.getText().toString().trim())) {
                    ToastUtils.showCenterToast("请输入新手机号");
                    return;
                }
                if (TextUtils.isEmpty(mEtCode2.getText().toString().trim())) {
                    ToastUtils.showCenterToast("请输入验证码");
                    return;
                }

                mRegisterBean.code2 = mEtCode2.getText().toString().trim();
                mRegisterBean.phone2 = mEtPhone2.getText().toString().trim();
                changePhone();
            } else {
                checkSms();
            }
            return;
        } else {

            if (TextUtils.isEmpty(mEtPsd.getText().toString().trim())) {
                ToastUtils.showCenterToast("请输入密码");
                return;
            }
            if (TextUtils.isEmpty(mEtPsd2.getText().toString().trim())) {
                ToastUtils.showCenterToast("请再次输入密码");
                return;
            }

            if (!mEtPsd.getText().toString().trim().equals(mEtPsd2.getText().toString().trim())) {
                ToastUtils.showCenterToast("两次密码不一致");
                return;
            }
            mRegisterBean.psd = mEtPsd.getText().toString().trim();
        }
        if (mType == 1) {
            register();
        } else if (mType == 3 || mType == 5) {
            changePsd();
        }
    }

    private void checkSms() {
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mEtPhone.getText().toString().trim());
        map.put("event", mType == 0 ? "register" : "resetpwd");
        map.put("captcha", mEtCode.getText().toString().trim());
        mPresenter.checkSmsCode(map);
    }


    private void register() {
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mRegisterBean.phone);
        map.put("password", mRegisterBean.psd);
        map.put("username", mRegisterBean.nickname);
        map.put("code", mRegisterBean.code);
        mPresenter.register(map);

    }

    private void changePhone() {
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mRegisterBean.phone2);
        map.put("captcha", mRegisterBean.code2);
        map.put("oldmobile", mRegisterBean.phone);
        map.put("oldcaptcha", mRegisterBean.code);
        mPresenter.changePhone(map);

    }

    private void changePsd() {
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mRegisterBean.phone);
        map.put("newpassword", mRegisterBean.psd);
        map.put("captcha", mRegisterBean.code);
        mPresenter.changePsd(map);
    }

    private void sendSMS() {

        if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入手机号");
            return;
        }
        mEtCode.requestFocus();
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mEtPhone.getText().toString().trim());
        if (mType == 0) {
            map.put("event", "register");
        } else if (mType == 2) {
            map.put("event", "resetpwd");
        } else if (mType == 4) {
            map.put("event", "resetpwd");
        } else if (mType == 6) {
            map.put("event", "changemobile");
        } else if (mType == 7) {
            map.put("event", "changenewmobile");
        }
        if (mType == 0) {
            mUserPresenter.hasNickName(mEtName.getText().toString().trim(), map, mTvSend);
        }else {
            mPresenter.sendSMS(map, mTvSend);
        }
    }

    private void sendSMS2() {

        if (TextUtils.isEmpty(mEtPhone2.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入新手机号");
            return;
        }
        mEtCode2.requestFocus();
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mEtPhone2.getText().toString().trim());
        map.put("event", "changenewmobile");
        mPresenter.sendSMS(map, mTvSend2);
    }

    //开启倒计时
    private void startTimer(TextView tv) {
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            private int counter = 60;

            public void run() {

                runOnUiThread(() -> {
                    if (counter > 0) {
                        tv.setText(String.format("%ds后重新发送", counter));
                    } else {
                        tv.setText("发送验证码");
                        tv.setEnabled(!TextUtils.isEmpty(mEtPhone.getText()));
                        tv.setTextColor(getResources().getColor(R.color.color_blue));
                        timer.cancel();
                    }

                    counter--;
                });
            }
        };
        timer.schedule(task, 0L, 1000L);
        tv.setEnabled(false);
        tv.setTextColor(getResources().getColor(R.color.color_99));


    }

    @Override
    protected void initPresenter() {
        mPresenter = new RegisterPresenter(this);
        mUserPresenter = new UserPresenter(this);
    }


    //注册成功 会返回用户信息，所以不再登录
    @Override
    public void registerSuccess(LoginBean loginBean) {
        ToastUtils.showCenterToast("注册成功");
        ConfigStorage.getInstance().saveUserBean(loginBean);
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_LOGIN_SUCCESS));
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();

    }


    @Override
    public void registerFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void sendSmsSuccess(TextView tv) {
        ToastUtils.showCenterToast("验证码已发送，请注意查收");
        startTimer(tv);
    }

    @Override
    public void sendSmsFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }


    @Override
    public void checkSmsSuccess() {
        startActivity(this, mType + 1, mRegisterBean);
    }

    @Override
    public void checkSmsFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void changeSuccess(String msg) {
        ToastUtils.showCenterToast(msg);
        //修改密码成功
        if (mType == 3 || mType == 5 || mType == 6) {
            StoreUtils.clear();
            startActivity(new Intent(this, LoginActivity.class));

        }

    }

    @Override
    public void changeFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void finish() {
        super.finish();
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_FINISH_REGISTER_ACTIVITY));
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_START_LOGIN_ACTIVITY:
            case MessageType.TYPE_ON_LOGIN_START:
                finish();
                break;
        }
    }

    @Override
    public void clearUserSuccess() {

    }

    @Override
    public void clearUserFail(String msg) {

    }

    @Override
    public void hasNickName(boolean isHasNickName, String name, Map<String, Object> body, TextView textView) {
        if (isHasNickName){
            mPresenter.sendSMS(body, textView);
        }else {
            ToastUtils.showCenterToast("该昵称已被占用，请更换昵称");
        }
    }

    @Override
    public void changeNameSuccess(boolean isChangeSuccess, String name) {

    }
}
